package 尚硅谷.juc.test17;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MyData {

    //标志位
    private volatile boolean flg=true;

    private AtomicInteger atomicInteger=new AtomicInteger();

    BlockingQueue<String> blockingQueue=null;

    public MyData(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    /**
     * 生产
     */
    public void myProd() throws InterruptedException {
        String data=null;
        boolean val;
        while (flg){
            data=atomicInteger.incrementAndGet()+"";
            val=blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if (val){
                log.info(Thread.currentThread().getName()+"插入队列"+data+"成功");
            }else {
                log.error(Thread.currentThread().getName()+"插入队列"+data+"失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        log.info(Thread.currentThread().getName()+"生产结束.............");
    }

    /**
     * 消费
     */
    public void myConsumer() throws InterruptedException {
        String poll;
        while (flg){
            poll= blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (poll==null||poll.equalsIgnoreCase("")){
                flg=false;
                log.info(Thread.currentThread().getName()+"超过2秒没取到数据，消费者退出");
                return;
            }
            log.info(Thread.currentThread().getName()+"取出得数据是："+poll);
        }
    }

    public void stop(){
        this.flg=false;
    }
}
